<?php
/**
 * Created by PhpStorm.
 * User: 牛赞赞
 * Date: 2021/2/1
 * Time: 10:02
 */

namespace App\Task;

use Psr\Container\ContainerInterface;
use Swoole\WebSocket\Server as WebSocketServer;

class RobotAssignTask
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * 分配机器人
     * @param $room_no
     */
    public function assignRobot($room_no){
        $game_conf  = config('game');
        $robot_conf  = config('robot');
        $room_wait_key      = sprintf($game_conf['user_room_wait'],$room_no);
        if(redis()->exists($room_wait_key)) {
            $wait_users  = json_decode(redis()->get($room_wait_key));
            $include_arr = array_diff($wait_users,$robot_conf['robots']);// 判断房间是否全是机器人
            if((count($wait_users) < 4) && !empty($include_arr)){
                // 人数未达到，定时器分配机器人到房间
                do{
                    $rand_no = array_rand($robot_conf['robots'],1);
                    $rand_account = $robot_conf['robots'][$rand_no];
                    $able = in_array($rand_account,$wait_users);
                    if(!$able){
                        $account = $rand_account;
                        // 开启计时器循环标签
                        $this->setRobotLoop($room_no,$account);

                        // 投递机器人计时器
                        $task = container()->get(RobotJoinTimerTask::class);
                        $task->robotJoinTimer($account,$room_no);
                    }
                }while($able);
            }
        }
    }

    /**
     * 设置机器人计数
     * @param $room_no
     * @param $num
     */
    protected function setRobotLoop($room_no,$num){
        $robot_conf = config('robot');
        $robot_loop_key = sprintf($robot_conf['user_room_robot'],$room_no);
        redis()->set($robot_loop_key,$num);
    }

}